<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1>UBSync: Test</h1>

    <canvas id="i-graph" width="600" height="200"></canvas>

    <!-- test code -->
    <script src="lib/ubsync.js"></script>
    <script>

      /**
       * measurement setup
       */
      var kGraphWidth = 600,
          kGraphHeight = 200;
      var kLoopCount = 25;

      /**
       * start audio stream to activate local clock
       */
      var g = UBSync.context.createGain();
      g.connect(UBSync.context.destination);


      /**
       * arrays for measurement and comparison of two timebase and timestamp
       */
      var bufferGDelta = [];
      var bufferLDelta = [];
      var bufferTimestamp = [];
      var prev_gNow = UBSync.GNow, // global now (from window.performance)
          prev_lNow = UBSync.LNow; // local now (from audio context)


      /**
       * capturing data
       */
      var cnt = kLoopCount;
      function loop(timestamp) {

        var gNow = UBSync.GNow,
            lNow = UBSync.LNow;

        bufferGDelta.push(gNow - prev_gNow);
        bufferLDelta.push(lNow - prev_lNow);
        bufferTimestamp.push(timestamp || 0.0);

        prev_gNow = gNow;
        prev_lNow = lNow;

        cnt--;
        if (cnt) {
          requestAnimationFrame(loop);
        } else {
          drawGraph();
        }
      }
      loop();


      /**
       * drawing graph
       */
      function drawGraph() {
        // canvas handle
        var cvs = document.getElementById('i-graph');
        var ctx2d = cvs.getContext('2d');

        // setting
        var xoffset = kGraphWidth / kLoopCount;

        // draw grid & label
        ctx2d.strokeStyle = "#ddd";
        ctx2d.fillStyle = "#aaa";
        ctx2d.font = "9pt Arial";
        ctx2d.beginPath();
        for (var i = 0; i < kLoopCount; i++) {
          ctx2d.moveTo(i * xoffset, 0);
          ctx2d.lineTo(i * xoffset, kGraphHeight);
          ctx2d.save();
          ctx2d.translate(i * xoffset, kGraphHeight);
          ctx2d.rotate(-Math.PI/2);
          ctx2d.fillText(bufferTimestamp[i].toFixed(3), 150, 10);
          ctx2d.restore();
        }
        ctx2d.stroke();

        // draw global delta
        ctx2d.beginPath();
        ctx2d.strokeStyle = "#000";
        ctx2d.moveTo(0, kGraphHeight);
        for (var i = 0; i < kLoopCount; i++) {
          var y = kGraphHeight - (bufferGDelta[i] * (kGraphHeight * 20));
          ctx2d.lineTo(i * xoffset, y);
        }
        ctx2d.stroke();

        // draw local delta
        ctx2d.beginPath();
        ctx2d.strokeStyle = "#f00";
        ctx2d.moveTo(0.0, kGraphHeight);
        for (var i = 0; i < kLoopCount; i++) {
          var y = kGraphHeight - (bufferLDelta[i] * (kGraphHeight * 20));
          ctx2d.lineTo(i * xoffset, y);
        }
        ctx2d.stroke();
      }

    </script>

  </body>
</html>